<template>
  <Cascader
    v-bind="$attrs"
    :options="options"
    :load-data="loadData"
    placeholder="Please select"
    :fieldNames="{
      label: 'city',
      value: 'city',
    }"
    change-on-select
  />
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { Cascader } from 'ant-design-vue';
  import { GetcitylistApi, GetArealistApi } from '/@/api/activityAdmin/index';
  import { userStore } from '/@/store/modules/user';
  interface Option {
    id: string | number;
    city: string;
    loading?: boolean;
    isLeaf?: boolean;
    children?: Option[];
  }
  export default defineComponent({
    name: 'AreaCascader',
    components: {
      Cascader,
    },
    setup() {
      const operatorId = ref<string>(userStore.getUserInfoByIdState.operatorId || '');
      let options = ref<Option[]>([]);
      console.log(operatorId);
      function getAreaList() {
        GetcitylistApi().then((res) => {
          if (res.code === 200) {
            res.data.forEach((item) => {
              item.isLeaf = false;
            });
            if (operatorId.value) {
              res.data = res.data.filter((item) => {
                return item.id == operatorId.value;
              });
            }
            options.value = res.data;
          }
        });
      }
      getAreaList();
      const loadData = (selectedOptions: Option[]) => {
        let childrenOptons: Option[] = [];
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        GetArealistApi(targetOption.id).then((res) => {
          if (res.code == 200) {
            res.data.area.forEach((item) => {
              const obj: Option = {
                id: item,
                city: item,
                isLeaf: true,
              };
              childrenOptons.push(obj);
            });
            targetOption.children = childrenOptons;
          }
          options.value = [...options.value];
          targetOption.loading = false;
        });
      };
      return {
        options,
        loadData,
      };
    },
  });
</script>
<style lang="less" scoped></style>
